package edu.bw.dao.impl;

import edu.bw.dao.ProductDao;
import edu.bw.mapper.ProductMapper;
import edu.bw.po.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("productDao")
public class ProductDaoImpl implements ProductDao {
    @Autowired
//    @Qualifier("queryRunner")
//    private QueryRunner qr;
    private JdbcTemplate jdbcTemplate;
    @Autowired
//    private ConnectionFactory connectionFactory;
    private ProductMapper productMapper;

    @Override
    public void updateProduct(Product product) {
        /*try {
            qr.update(connectionFactory.getConnection(),
                    "UPDATE spring.product p " +
                    "SET p.pname=?,p.price=?,p.category=?" +
                    "WHERE p.pid=?",
                    product.getPname(),
                    product.getPrice(),
                    product.getCategory(),
                    product.getPid());
//            int i =1/0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }*/
        jdbcTemplate.update(
                "UPDATE spring.product p " +
                        "SET p.pname=?,p.price=?,p.category=? " +
                        "WHERE p.pid=?",
                product.getPname(),
                product.getPrice(),
                product.getCategory(),
                product.getPid());
    }

    @Override
    public void deleteProductById(int pid) {
        /*try {
            qr.update(connectionFactory.getConnection(),
                    "DELETE FROM spring.product WHERE pid=?",
                    pid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }*/
        jdbcTemplate.update(
                "DELETE FROM spring.product WHERE pid=?",
                pid);
    }

    @Override
    public List<Product> findAllProducts() {
        /*try {
            return qr.query("SELECT * FROM spring.product",
                    new BeanListHandler<Product>(Product.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    */
        return jdbcTemplate.query(
                "SELECT * FROM spring.product",
                productMapper);
    }
}
